package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.adapter.CarListAdapter;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.entity.NSDTO;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.entity.VehicleInfoList;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.JsonParser;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.utils.Utility;
import com.umeng.analytics.MobclickAgent;

/**
 * 年审
 * @author kuanter
 *
 */
public class YearChargeActivity extends BaseActivity_NoBar {
	LayoutInflater factory;
	RelativeLayout car_info;
	
	TextView tv_clxx; //车辆信息
	TextView tv_ppxx; //品牌信息
	
	RelativeLayout choseCar;  //选择车辆
	RelativeLayout chosetc;   //选择套餐
	TextView tv_tclx;	//选择的套餐类型
	TextView nsjf;		//选择的套餐的积分
	
	ProApplication application;
	List<VehicleInfo> vehicleInfos;
	
	public static final int choseCarRequest = 1;
	
	String cityCode = "";
	
	NSDTO nsdto;
	
	String tclx = "";
	String carID = "";
	
	PackageAdapter packageAdapter;
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
	Handler ns_handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				nsdto = JsonParser.getNS(json);
				if(packageAdapter != null) {
					packageAdapter.notifyDataSetChanged();
				}
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.car_yearcharge);
		Intent intent = getIntent();
		cityCode = intent.getStringExtra("cityID");
		cityCode = SharePrefenceUtil.getCityID(this);
		showProgress("正在加载数据...");
		
		factory = getLayoutInflater();
		application = (ProApplication) getApplication();
		if(application.getList_vehicleInfo() != null) {
			vehicleInfos = application.getList_vehicleInfo();
			initView();
		} else {
			DataLoader loader = new DataLoader(this);
			String url = MainConstants.HOST_test + HttpConfigAPI.FINDVEHICLE;
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair params = new BasicNameValuePair("vehicleInfo.userId", SharePrefenceUtil.getUserID(YearChargeActivity.this) + "");
			list.add(params);
			
			if(CheckNetworkState()) {
				loader.DisplayData(url, list, mHandler, "", false);
				initView();
			}
		}
		
		DataLoader loaderInspection = new DataLoader(this);
		String url_in = MainConstants.HOST_test + HttpConfigAPI.findTaoCan;
		List<NameValuePair> ns_list = new ArrayList<NameValuePair>();
		NameValuePair params_ns = new BasicNameValuePair("cityCode", cityCode);
		ns_list.add(params_ns);
		loaderInspection.DisplayData(url_in, ns_list, ns_handler, "", false);
		
		
	}

	/**
	 * 初始化view
	 */
	private void initView() {
		car_info = (RelativeLayout) findViewById(R.id.car_info_top);
		TextView title = (TextView) car_info.findViewById(R.id.top_middle);
		title.setText("年审服务");
		
		LinearLayout home_chose_City = (LinearLayout) car_info.findViewById(R.id.home_chose_City);
		home_chose_City.setVisibility(View.GONE);
		
		tv_clxx = (TextView) findViewById(R.id.tv_clxx);
		tv_ppxx = (TextView) findViewById(R.id.tv_ppxx);
		
		choseCar = (RelativeLayout) findViewById(R.id.choseCar);
		choseCar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				Builder builder = new AlertDialog.Builder(YearChargeActivity.this);
				View dialog_view = getLayoutInflater().inflate(R.layout.yearcharge_cars, null);
				ListView list_cars = (ListView) dialog_view.findViewById(R.id.cars);
				ChargeAdapter adapter = new ChargeAdapter();
				list_cars.setAdapter(adapter);
//				Utility.setListViewHeightBasedOnChildren(list_cars);
				
				RelativeLayout other_car = (RelativeLayout) dialog_view.findViewById(R.id.other_car);
				other_car.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View view) {
						if(dialog != null) {
							dialog.dismiss();
						}
						/*Intent intent = new Intent(YearChargeActivity.this,
								TjclActivity.class);*/
						Intent intent = new Intent(YearChargeActivity.this,
								NSAddCar.class);
						intent.putExtra("userID", SharePrefenceUtil.getUserID(YearChargeActivity.this) + "");
						startActivityForResult(intent, choseCarRequest);
					}
				});
				
				
				builder.setTitle("请选择车辆");
				dialog = builder.create();
				dialog.setView(dialog_view,0,0,0,0);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});
		
		chosetc = (RelativeLayout) findViewById(R.id.chosetc);
		chosetc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Builder build = new Builder(YearChargeActivity.this);
				View dialog_package_view = factory.inflate(R.layout.package_list, null);
				ListView packages = (ListView) dialog_package_view.findViewById(R.id.packages);
				packageAdapter = new PackageAdapter();
				packages.setAdapter(packageAdapter);
				build.setTitle("请选择套餐");
				dialog_package = build.create();
				dialog_package.setView(dialog_package_view,0,0,0,0);
				dialog_package.setCanceledOnTouchOutside(true);
				
				if(nsdto == null) {
					DataLoader loaderInspection = new DataLoader(YearChargeActivity.this);
					String url_in = MainConstants.HOST_test + HttpConfigAPI.findTaoCan;
					List<NameValuePair> ns_list = new ArrayList<NameValuePair>();
					NameValuePair params_ns = new BasicNameValuePair("cityCode", cityCode);
					ns_list.add(params_ns);
					loaderInspection.DisplayData(url_in, ns_list, ns_handler, "", false);
				}
				
				dialog_package.show();
			}
		});
		
		tv_tclx = (TextView) findViewById(R.id.tv_tclx);
		nsjf = (TextView) findViewById(R.id.nsjf);
	}
	
	AlertDialog dialog_package;
	AlertDialog dialog;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == choseCarRequest && resultCode == 0) {
			if(data != null) {
				String carCard = data.getStringExtra("carCard");
				String carInfo_pp = data.getStringExtra("carInfo_pp");
				String carInfo_xh = data.getStringExtra("carInfo_xh");
				tv_clxx.setText(carCard.substring(0, 2)  + " — " + carCard.substring(2, carCard.length()));
				tv_ppxx.setText(carInfo_pp + "-" + carInfo_xh);
				carID = data.getStringExtra("vehicleId");
				VehicleInfo info1 = new VehicleInfo();
				info1.setId(carID);
				info1.setLicensePlateNumber(carCard);
				info1.setVehicleBrand(carInfo_pp);
				info1.setVehicleModels(carInfo_xh);
				if(vehicleInfos != null) {	//---TODO
					vehicleInfos.add(info1);
				} else {
					vehicleInfos = new ArrayList<VehicleInfo>();
					vehicleInfos.add(info1);
				}
				CarListAdapter.vehicleInfos = vehicleInfos;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}

	/**
	 * 开始支付
	 * @param view
	 */
	public void pay(View view) {
		if(carID.equals("") || tclx.equals("")) {
			showToast("请选择车辆和套餐");
		} else {
			showProgress("正在支付,请稍后...");
			//发送请求:根据回复的status显示支付成功还是失败
			DataLoader loader = new DataLoader(YearChargeActivity.this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair param_id = new BasicNameValuePair("userId",SharePrefenceUtil.getUserID(YearChargeActivity.this) + "");
			NameValuePair param_cardID = new BasicNameValuePair("id",carID);
			NameValuePair vitype = new BasicNameValuePair("VIType", tclx);
			NameValuePair shopID = new BasicNameValuePair("shopId",nsdto.getId());
			params.add(param_id);
			params.add(param_cardID);
			params.add(shopID);
			params.add(vitype);
			loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.payns, params, mHandler_pay, "", false);
			
			/*Intent fail_intent = new Intent(YearChargeActivity.this, PayFailActivity.class);
			fail_intent.putExtra("type", type_id);
			if(test == 0) {
				fail_intent.putExtra("status", PayFailActivity.status_fail);
			} else {
				fail_intent.putExtra("status", PayFailActivity.status_success);
			}
			test++;
			startActivity(fail_intent);*/
		}
	}
	
	public void exit(View view) {
		finish();
	}
	
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				Log.i("bbb", json);
				VehicleInfoList vehicleInfoList = new VehicleInfoList(json);
				vehicleInfos = vehicleInfoList.getVehicleInfoList();
				if(application != null) {
					application.setList_vehicleInfo(vehicleInfos);
					CarListAdapter.vehicleInfos = application.getList_vehicleInfo();
				}
				if(nsdto != null) {
					finishProgress();
				}
			} else if(msg.what == HttpTask.RESULT_ERROR){
				showToast("服务器连接失败");
				finishProgress();
			}
			super.handleMessage(msg);
		}
		
	};
	
	Handler mHandler_pay = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				Log.i("aaa", json + "-----年审");
				try {
					Intent fail_intent = new Intent(YearChargeActivity.this, PayFailActivity.class);
					JSONObject jo_result = new JSONObject(json);
					String message_back = jo_result.optString("errorMsg");
					if(StringUtils.isSuccess(json)) {
						fail_intent.putExtra("status", PayFailActivity.status_success);
						if(ProApplication.getInstance().getCardInfoList() != null) {
							ProApplication.getInstance().getCardInfoList().clear();
//							List<CardInfo> listCard = ProApplication.getInstance().getCardInfoList();
//							listCard = null;
						}
						startActivity(fail_intent);
						finish();
					} else {
						fail_intent.putExtra("status", PayFailActivity.status_fail);
//						fail_intent.putExtra("status", PayFailActivity.status_success);
						fail_intent.putExtra("message_back", message_back);
						
						startActivity(fail_intent);
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				showToast("申请失败，您的网络状况不好");
			}
			super.handleMessage(msg);
		}
		
	};
	
	class ChargeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			int size = 0;
			if(vehicleInfos != null) {
				size = vehicleInfos.size();
			}
			return size;
		}

		@Override
		public Object getItem(int position) {
			
			return vehicleInfos == null ? position : vehicleInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			if(view == null) {
				view = factory.inflate(R.layout.car_item, null);
			}
			TextView car_id = (TextView) view.findViewById(R.id.car_id);
			RadioButton car_number = (RadioButton) view.findViewById(R.id.car_number);
			
			car_id.setText(vehicleInfos.get(position).getId());
			car_number.setText(vehicleInfos.get(position).getLicensePlateNumber());
			
			RelativeLayout rl_yjxb = (RelativeLayout) view.findViewById(R.id.rl_yjxb);
			rl_yjxb.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(dialog != null) {
						dialog.dismiss();
					}
					
					carID = vehicleInfos.get(position).getId();
					
					tv_clxx = (TextView) findViewById(R.id.tv_clxx);
					tv_ppxx = (TextView) findViewById(R.id.tv_ppxx);
					
					if(vehicleInfos.get(position) != null) {
						String str = vehicleInfos.get(position).getLicensePlateNumber()
								.substring(0, 2).equals("") ? "暂无信息 — " : vehicleInfos.get(position).getLicensePlateNumber().substring(0, 2);
						String str1 = vehicleInfos.get(position).getLicensePlateNumber()
								.substring(2,vehicleInfos.get(position).getLicensePlateNumber().length()).equals("") ? "暂无信息"
								: vehicleInfos.get(position).getLicensePlateNumber().substring(
												2,vehicleInfos.get(position).getLicensePlateNumber().length());
						
						if (!str.equals("暂无信息 — ")) {
							if (YearChargeActivity.this.isHanZi(str.substring(0, 1))
									|| YearChargeActivity.this.isE(str.substring(1, 1))) {
								tv_clxx.setText(str + " — ");// tv_clxx
								tv_clxx.append(str1);
							} else {
								tv_clxx.setText("暂无信息 — ");
								if (!str1.equals("暂无信息")) {
									tv_clxx.append(vehicleInfos.get(position).getLicensePlateNumber());
								} else {
									tv_clxx.append("暂无信息");
								}
							}
						} else {
							tv_clxx.setText(str);
						}
						//
						tv_ppxx.setText(vehicleInfos.get(position).getVehicleBrand()
								.equals("") ? "暂无信息 — " : vehicleInfos.get(position).getVehicleBrand() + " — ");
						
						tv_ppxx.append(vehicleInfos.get(position).getVehicleModels()
								.equals("") ? "暂无信息" : vehicleInfos.get(position).getVehicleModels());
						
					}
					
					
				}
			});
			
			if(position == 0) {
				rl_yjxb.setBackgroundResource(R.drawable.setting_item_top_corner);
			} else {
				rl_yjxb.setBackgroundResource(R.drawable.setting_item_no_corner);
			}
			
			return view;
		}
		
	}
	
	class PackageAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if(nsdto == null) {
				return 0;
			} else {
				return nsdto.getServiceInfoList() == null ? 0 : nsdto.getServiceInfoList().size();
			}
		}

		@Override
		public Object getItem(int i) {
			return nsdto.getServiceInfoList().get(i);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(final int i, View view, ViewGroup viewgroup) {
			if(view == null) {
				view = factory.inflate(R.layout.package_item, null);
			}
			
			RelativeLayout re_package = (RelativeLayout) view.findViewById(R.id.re_package);
			
			final RadioButton package_type = (RadioButton) view.findViewById(R.id.package_type);
			
			final TextView package_jifen = (TextView) view.findViewById(R.id.package_jifen);
			package_type.setText(nsdto.getServiceInfoList().get(i).getServiceName());
			package_jifen.setText(nsdto.getServiceInfoList().get(i).getFacePrice());
			
			if(i == 0) {
				re_package.setBackgroundResource(R.drawable.setting_item_top_corner);
			} else if(i == nsdto.getServiceInfoList().size() - 1) {
				re_package.setBackgroundResource(R.drawable.setting_item_bottom_corner);
			} else {
				re_package.setBackgroundResource(R.drawable.setting_item_no_corner);
			}
			
			re_package.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					tv_tclx.setText(package_type.getText().toString());
					nsjf.setText(package_jifen.getText().toString());
					
					tclx = nsdto.getServiceInfoList().get(i).getId();
					if(dialog_package != null) {
						dialog_package.dismiss();
					}
				}
			});
			
			return view;
		}
		
	}
	
}
